package payment

import (
	"cloud_android_backend/pkg/config"
	"context"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"log"
	"time"
)

type WechatPay struct {
	Amount          float64
	Remark          string
	Description     string
	OutTradeNo      string
	QrCodeStr       string
	WechatPayConfig config.WechatPayConfig
}

func (w *WechatPay) Payment() (string, error) {

	wechatPayConfig := w.WechatPayConfig
	//mchID := "1716855971"
	//mchCertSerialNumber := "7EA87FC59A92C7A44842A50D09A4BD4E6BDD7EC4"
	//apiV3Key := "hd6Tjdwqm28HBioSjd9wqermdfH0PlsL" // 微信商户平台上配置的API v3密钥
	//appID := "wxc2a222c61155056e"
	//var wechatpayPublicKeyID string = "PUB_KEY_ID_0117168559712025051400211938002002" // 微信支付公钥ID
	// 加载商户私钥
	privateKey, err := utils.LoadPrivateKeyWithPath(wechatPayConfig.PrivateKeyPath) //"C:\\Users\\admin\\GolandProjects\\container_manager\\cert\\apiclient_key.pem"
	if err != nil {
		log.Printf("load private key err: %v", err)
		return "", err
	}
	wechatpayPublicKey, err := utils.LoadPublicKeyWithPath(wechatPayConfig.PublicKeyPath) //"C:\\Users\\admin\\GolandProjects\\container_manager\\cert\\pub_key.pem"
	if err != nil {
		return "", err
	}

	opts := []core.ClientOption{
		option.WithWechatPayPublicKeyAuthCipher(
			wechatPayConfig.MchID,
			wechatPayConfig.MchCertSerialNumber, privateKey,
			wechatPayConfig.PublicKeyID, wechatpayPublicKey),
	}

	client, err := core.NewClient(context.Background(), opts...)
	if err != nil {
		log.Printf("new wechat client err: %v", err)
		return "", err
	}

	svc := native.NativeApiService{Client: client}

	resp, result, err := svc.Prepay(context.Background(), native.PrepayRequest{
		Appid:       core.String(wechatPayConfig.AppID),
		Mchid:       core.String(wechatPayConfig.MchID),
		Description: core.String(w.Description),
		OutTradeNo:  core.String(w.OutTradeNo),
		NotifyUrl:   core.String(wechatPayConfig.NotifyUrl),
		Amount: &native.Amount{
			Total:    core.Int64(1), // 单位：分
			Currency: core.String("CNY"),
		},
		TimeExpire: core.Time(time.Now().Add(5 * time.Minute)), //5分钟超时
	})
	if err != nil {
		log.Printf("prepay err: %v, %+v", err, result)
		return "", err
	}
	w.QrCodeStr = *resp.CodeUrl
	// 返回的是二维码URL
	fmt.Printf("成功下单，二维码链接：%s\n", *resp.CodeUrl)
	return *resp.CodeUrl, nil
}

func (w *WechatPay) GetResultType() ResultType {
	return QrcodeStr
}

func (w *WechatPay) GetResult() string {
	return w.QrCodeStr
}
